const api = require('../../../utils/api')

Page({
  data: {
    id: null,
    imageUrl: '',
    categories: [],
    categoryIndex: 0,
    form: {
      name: '',
      categoryId: '',
      price: '',
      stock: '',
      description: '',
      isCarousel: false,
      isRecommended: false,
      isHot: false,
      carouselSort: 0,
      recommendSort: 0
    }
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      // 先加载分类，再加载商品
      this.loadCategories().then(() => {
        this.loadProduct(options.id)
      })
    } else {
      this.loadCategories()
    }
  },

  // 加载商品分类
  async loadCategories() {
    try {
      const res = await api.getCategories()
      if (res.success) {
        this.setData({ categories: res.data })
      }
    } catch (error) {
      console.error('加载分类失败:', error)
      wx.showToast({
        title: '加载分类失败',
        icon: 'none'
      })
    }
  },

  // 加载商品详情
  async loadProduct(id) {
    try {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })

      const res = await api.getProductDetail(id)
      if (res.success) {
        const product = res.data
        // 找到分类索引
        let categoryIndex = this.data.categories.findIndex(
          c => c.id === product.category.id
        )
        
        console.log('商品分类ID:', product.category.id)
        console.log('可用分类:', this.data.categories)
        console.log('找到的分类索引:', categoryIndex)
        
        // 如果没找到，使用商品本身的分类ID
        if (categoryIndex === -1) {
          categoryIndex = 0
          // 如果categories为空或找不到对应分类，可能需要重新加载分类或提示用户
          wx.showToast({
            title: `未找到对应分类：${product.category.name}`,
            icon: 'none'
          })
        }

        this.setData({
          imageUrl: product.imageUrl,
          categoryIndex: categoryIndex,
          form: {
            name: product.name,
            categoryId: product.category.id, // 直接使用商品返回的分类ID
            price: product.price,
            stock: product.stock,
            description: product.description,
            isCarousel: product.isCarousel || false,
            isRecommended: product.isRecommended || false,
            isHot: product.isHot || false,
            carouselSort: product.carouselSort || 0,
            recommendSort: product.recommendSort || 0
          }
        })
      }
    } catch (error) {
      console.error('加载商品详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadImage(tempFilePath);
      }
    });
  },

  // 上传图片
  async uploadImage(filePath) {
    wx.showLoading({
      title: '上传中...',
      mask: true
    });

    try {
      // 使用api.js中的统一上传方法
      const uploadResult = await api.uploadImage(filePath, true);

      if (uploadResult.success) {
        this.setData({
          imageUrl: uploadResult.data.url,
          'form.imageUrl': uploadResult.data.url
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.message || '上传失败');
      }
    } catch (error) {
      console.error('上传失败:', error);
      wx.showToast({
        title: '上传失败：' + (error.message || '未知错误'),
        icon: 'none',
        duration: 2000
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 分类选择
  onCategoryChange(e) {
    const index = e.detail.value
    this.setData({
      categoryIndex: index,
      'form.categoryId': this.data.categories[index].id
    })
  },

  // 展示设置开关
  onCarouselChange(e) {
    this.setData({
      'form.isCarousel': e.detail.value
    })
  },

  onRecommendChange(e) {
    this.setData({
      'form.isRecommended': e.detail.value
    })
  },

  onHotChange(e) {
    this.setData({
      'form.isHot': e.detail.value
    })
  },

  // 表单提交
  async handleSubmit(e) {
    const formData = e.detail.value
    const { form, id, imageUrl, categories, categoryIndex } = this.data

    // 表单验证
    if (!imageUrl) {
      wx.showToast({
        title: '请上传商品图片',
        icon: 'none'
      })
      return
    }

    if (!formData.name || !formData.price || !formData.stock) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    // 确保有有效的分类
    if (!categories || categories.length === 0) {
      wx.showToast({
        title: '未加载分类数据',
        icon: 'none'
      })
      return
    }

    // 构建提交数据
    const submitData = {
      name: formData.name,
      categoryId: form.categoryId || categories[categoryIndex].id, // 优先使用表单中保存的分类ID
      price: parseFloat(formData.price),
      stock: parseInt(formData.stock),
      description: formData.description,
      imageUrl,
      isCarousel: form.isCarousel,
      isRecommended: form.isRecommended,
      isHot: form.isHot,
      carouselSort: form.isCarousel ? parseInt(formData.carouselSort) : 0,
      recommendSort: form.isRecommended ? parseInt(formData.recommendSort) : 0
    }

    console.log('提交的商品数据:', submitData)

    try {
      wx.showLoading({
        title: '保存中...',
        mask: true
      })

      let res
      if (id) {
        res = await api.updateProduct(id, submitData)
      } else {
        res = await api.createProduct(submitData)
      }

      if (res.success) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.message || '保存失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存商品失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  }
}) 